package app;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.helper.DateUtil;
import com.example.menhoo.toollibrary.common.utils.BitmapUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import application.AppApplication;
import application.HttpUrlConstant;
import application.KeyConstant;
import interfaces.IReturnObject;
import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import model.LoginUser;

/**
 * 闪屏页面
 * Created by yanglei on 15/12/27.
 */


public class SplashScreen extends AppActivity {

    ImageView AppIconTitle;

    ImageView AppIconBackground;

    TextView AppDesc;

    long time=0;
    long minWaitTime=1300;//毫秒
    LoginUser userDB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //先不运行signalr连接服务
        setRunSignalrService(false);
        super.onCreate(savedInstanceState);

        //
        setContentView(R.layout.splash_screen);
        try{
            AppIconTitle = (ImageView)findViewById(R.id.AppIconTitle);
            AppIconBackground = (ImageView)findViewById(R.id.AppIconBackground);
            AppDesc = (TextView)findViewById(R.id.AppDesc);
        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }

        setImmerseStatusBar(Color.parseColor("#000000"));
        setTitleDisplay(false);

        try {
            userDB = getDB().findFirst(LoginUser.class);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

        try {

            AppIconTitle.setImageBitmap(BitmapUtil.getRoundedCornerBitmap(BitmapFactory.decodeStream(this.getResources()
                    .openRawResource(R.raw.ic_launcher)), 15f));
            AppIconBackground.setImageBitmap(BitmapFactory.decodeStream(this.getResources().openRawResource(R.raw.app_icon_background)));

//            AppDesc.setText(AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppDesc));
            //2018.5.16 修改为新吴移动政务
            AppDesc.setText(R.string.app_name);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

        time = DateUtil.Now().getTime();

        InitImageValue(new IReturnObject() {
            @Override
            public void returnResult(Object result) {

                if (AppApplication.getSession() == null || AppApplication.getSession().equalsIgnoreCase("")) {
                    //没有登陆
                    //看看是否能自动登陆
                    if(userDB!=null && userDB.autoLogin){
                        Login(userDB.userName, userDB.pwd, new IReturnObject<Boolean>() {
                            @Override
                            public void returnResult(Boolean result) {
                                if(result){
                                    //自动登陆成功
                                    openMainActivity();
                                }
                                else{
                                    //自动登陆失败
                                    openLoginActivity();
                                }
                            }
                        },false);
                    }
                    else{
                        //无法自动登陆
                        openLoginActivity();
                    }
                } else {
                    //已经登陆
                    openMainActivity();
                }
            }
        });
    }

    private void openLoginActivity(){

        long off = DateUtil.Now().getTime()-time;
        long delayTime = 0;
        if(off>=minWaitTime){
            delayTime = 0;
        }
        else{
            delayTime = minWaitTime - off;
        }
//        MessageUtil.showLongToast(SplashScreen.this, "延迟打开："+delayTime);
        HandlerUtil.runOnUiThreadDelay(new Runnable() {
            @Override
            public void run() {

                Intent it = new Intent(SplashScreen.this, Login.class);
                startActivity(it);

                overridePendingTransition(android.support.v7.appcompat.R.anim.abc_fade_in, android.support.v7.appcompat
                        .R.anim
                        .abc_fade_out);
                onBackPressed();

            }
        }, delayTime);
    }
    private void openMainActivity(){
        long off = DateUtil.Now().getTime()-time;
        long delayTime = 0;
        if(off>=minWaitTime){
            delayTime = 0;
        }
        else{
            delayTime = minWaitTime - off;
        }
//        MessageUtil.showLongToast(SplashScreen.this, "延迟打开："+delayTime);
        HandlerUtil.runOnUiThreadDelay(new Runnable() {
            @Override
            public void run() {

                Intent it = new Intent(SplashScreen.this, Main.class);
                startActivity(it);

                overridePendingTransition(android.support.v7.appcompat.R.anim.abc_fade_in, android.support.v7.appcompat
                        .R.anim
                        .abc_fade_out);
                onBackPressed();

            }
        }, delayTime);
    }

    public static void InitImageValue(final IReturnObject function){
        HttpUtils http = new HttpUtils(7 * 1000);
        http.send(HttpMethod.GET, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.GetSysInfo), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                if(!Check.isEmpty(result)){
                    try {
                        LogUtils.e("splash页面的请求结果："+result);
                        JSONObject jsonObject = new JSONObject(result);
                        if(jsonObject.getBoolean("Succeed")){
                            JSONObject data = jsonObject.getJSONObject("Data");
                            String Title = data.getString("Title");
                            String Version = data.getString("Version");
                            String Logo = data.getString("Logo");
                            String LogonBg = data.getString("LogonBg");

                            AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.AppDesc, Title);
                            AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.AppIconTitle, Logo);
                            AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.AppIconBackground, LogonBg);
                        }

                    } catch (JSONException e) {
                        LogUtils.e(e.getMessage()+"");
                    }
                }

                if(function!=null){
                    function.returnResult(null);
                }



            }

            @Override
            public void onFailure(HttpException e, String s) {
                if(function!=null){
                    function.returnResult(null);
                }
            }
        });
    }
}
